package com.podcstr.dao;

import com.podcstr.entity.Series;
import org.apache.log4j.Logger;

import javax.persistence.NoResultException;
import java.util.Date;
import java.util.List;

/**
 * @author azim
 * @since 5/16/13 
 */

public class SeriesDaoImpl extends GenericDaoImpl<Series, Long> implements SeriesDao {

    private final Logger log = Logger.getLogger(UserDaoImpl.class);

    @Override
    public void toggleAccess(long seriesID) {

        Series series = getEntityManager().find(Series.class, seriesID);

        if (series.isAccessable() == true) {
            series.setAccessable(false);
        } else {
            series.setAccessable(true);
        }
        getEntityManager().merge(series);

        log.info(new Date() + " : Series with id : " + seriesID + " has now accessable value of " + series.isAccessable());
    }

    @Override
    public Series findBySeriesName(String seriesName) {

        Series series = null;

        try {

            series = (Series) (getEntityManager().createNamedQuery("tb_series.findByName").setParameter("name", seriesName).getSingleResult());
        } catch (NoResultException noe) {

            series = null;
        }

        if (series != null) {
            log.info(new Date() + " : Returning Series with name : " + seriesName);
        }
        return series;
    }

    @Override
    public List<Series> findByUserId(long userId) {

        List<Series> serieses = getEntityManager().createQuery("SELECT p FROM Series p WHERE p.user.id=:userId")
                .setParameter("userId", userId)
                .getResultList();

        if (serieses.size() != 0) {
            log.info(new Date() + " : Returning list of Series by user with id : " + userId);
        } else {
            serieses = null;
        }

        return serieses;
    }

    @Override
    public List<Series> findByTags(String tag) {

        List<Series> serieses = getEntityManager().createQuery("SELECT p FROM Series p WHERE LOCATE(p.tags, :tag) > 0")
                .setParameter("tag", tag)
                .getResultList();

        if (serieses.size() != 0) {
            log.info(new Date() + " : Returning list of Series by tag : " + tag);
        } else {
            serieses = null;
        }

        return serieses;
    }
}
